﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using DataLib.Accounts.Bus;
using System.Web.Script.Serialization;
using DataLib.BLL;
using DataLib.Model;

namespace Ewts.ashx
{
    /// <summary>
    /// ProduceMaterial 的摘要说明
    /// </summary>
    public class ProduceMaterial : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            JavaScriptSerializer serializer = new JavaScriptSerializer();

              string result = "";
              string insid = context.Request["insid"];

              DataLib.BLL.Productions bll = new Productions();
            //barcode islocak修改
            if (context.Request["barcodeid"]!=null && context.Request["barcodeid"].Trim() != "")
            {
                string id = "";
                string islock = "";
                id = context.Request["id"].Trim();
                if (context.Request["islock"].Trim() != "")
                {
                    islock = context.Request["islock"].Trim();
                }

                DataLib.Model.BarCode barcodeMode = new DataLib.BLL.BarCode().GetModel(Convert.ToInt32(id));
                if (islock == "1")
                {
                    barcodeMode.isLocak = true;
                    result = "已锁定";
                }
                else
                {
                    barcodeMode.isLocak = false;
                    result = "取消锁定";
                }

                if ((new DataLib.BLL.BarCode().Update(barcodeMode)) == true)
                    result += "成功！";
                else
                    result += "失败！";
            }
            else if (context.Request["delbarid"] != null && context.Request["delbarid"].Trim() != "")
            {
               
              
                int bid = int.Parse(context.Request["delbarid"].Trim());
                result = deleteByid(bid);
                
            }
            else if (context.Request["barid"] != null && context.Request["barid"].Trim() != "")
            {
                result = GetJsonByBarid(int.Parse(context.Request["barid"].Trim()));
            }
            else
            {
                //插入记录
                DataLib.BLL.InStorage bllIn = new DataLib.BLL.InStorage();
                DataLib.Model.InStorage inModel = new DataLib.Model.InStorage();
                DataLib.Model.lingniaoItems lingModel = new DataLib.Model.lingniaoItems();
                //DataLib.Model.sc_xh scXhMode = new DataLib.Model.sc_xh();


                //入库单id
                if (string.IsNullOrEmpty(insid) || insid == "0")
                {
                    inModel = AddInStorage(context);
                    insid = inModel.id.ToString();
                }
                else
                {
                    inModel = new DataLib.BLL.InStorage().GetModel(Convert.ToInt32(insid));
                }

                string nwt = context.Request["nwt"];
                string total = context.Request["weight"];

                //验证是否超重
               
                decimal o_total = decimal.Parse(total);
                decimal i_total = bll.GetInsTotal(insid);
                decimal b_nwt = decimal.Parse(nwt);
                if (o_total < i_total + b_nwt)
                {
                    result = "-2";
                }
                else
                {
                    DataLib.Model.BarCode barModel = new DataLib.Model.BarCode();
                    barModel = GetBarCode(context, insid);
                    lingModel = AddLingniaoItems(context, inModel, (int)barModel.id);
                    //AddScXh(inModel, lingModel);

                    inModel.instotal = i_total + b_nwt;
                    result += serializer.Serialize(barModel);
                    result += ",";
                    result += serializer.Serialize(inModel);
                    result = "[" + result + "]";
                    // OutStorageSetStatus(context);
                }

            }
    
            context.Response.Write(result);
        }

        /// <summary>
        /// 添加新的领料单
        /// </summary>
        public DataLib.Model.InStorage AddInStorage(HttpContext context)
        {
            DataLib.Model.InStorage inModel = new DataLib.Model.InStorage();

            //string outvloadnum = "";

            if (context.Request["oper"] != null)
            {
                inModel.Operator = context.Request["oper"].Trim();
            }
            if (context.Request["islocak"] != null && context.Request["islocak"].Trim() != "")
            {
                inModel.islock = Boolean.Parse(context.Request["islocak"]);
            }
            if (context.Request["inDepart"] != null && context.Request["inDepart"].Trim() != "")
            {
                inModel.InDepart = context.Request["inDepart"].Trim();
            }
            if (context.Request["outDepart"] != null && context.Request["outDepart"].Trim() != "")
            {
                inModel.OutDepart = context.Request["outDepart"].Trim();
            }
            if (context.Request["month"] != null && context.Request["month"].Trim().Length == 6)
            {
                inModel.clearingmonth = context.Request["month"].Trim();
            }
            inModel.instoragetime = DateTime.Now;
            inModel.status = 11;    //待领料
            inModel.mechanerr = 0; 
            inModel.cjoid = int.Parse(getObjTostring(context.Request["cjoid"], "0"));
            inModel.vloadnum= getObjTostring(context.Request["loadnum"], "0");
            if (context.Request["outid"] != null && context.Request["outid"].Trim() != "0")
            {
                DataLib.BLL.OutStorage obll = new DataLib.BLL.OutStorage(); 
                
                inModel.outid = int.Parse(context.Request["outid"].Trim());
                DataLib.Model.OutStorage omodel = obll.GetModel(inModel.outid);
                inModel.outno = omodel.id.ToString();
            }
           
            string wrlno = "";
            wrlno = Code.NumGeneration.GetSerialNum("RB", "InCode");
            inModel.wrlno = wrlno;

            DataLib.BLL.Productions bll = new Productions();
            inModel.id = bll.Save(inModel);
            return inModel;

        }

        /// <summary>
        /// 添加barcode并返回barcode的实体对象
        /// </summary>
        /// <param name="context"></param>
        /// <param name="inModel"></param>
        /// <returns></returns>
        public DataLib.Model.BarCode GetBarCode(HttpContext context,string insid)
        {
            string loadnum = "";
            int loadnumid = 0;
            DataLib.BLL.InStorage bllins = new DataLib.BLL.InStorage();
            DataLib.Model.InStorage modelins = bllins.GetModel(int.Parse(insid));
            if (context.Request["loadnum"] != null && context.Request["loadnum"].Trim() != "")
            {
                loadnum = getObjTostring(context.Request["loadnum"]);
                DataLib.Model.LoadNum loadmodel = new DataLib.BLL.LoadNum().GetLoadID(loadnum);
                if (loadmodel != null && loadmodel.id > 0)
                    loadnumid = (int)loadmodel.id;
            }

            string strtemp = null;
            DataLib.Model.BarCode bmodel = new DataLib.Model.BarCode();
            bmodel.cjoid = int.Parse(getObjTostring(context.Request["cjoid"], "0"));
            if (loadnumid > 0)
                bmodel.loadnumid = loadnumid;
            else
                bmodel.loadnumid = 0;
            bmodel.comeunder = getObjTostring(context.Request["comeunder"],"");
            bmodel.gwt = decimal.Parse(getObjTostring(context.Request["gwt"], "0"));
            bmodel.nwt = decimal.Parse(getObjTostring(context.Request["nwt"], "0"));
            bmodel.tare1 = decimal.Parse(getObjTostring(context.Request["tare1"], "0"));
            bmodel.tare2 = decimal.Parse(getObjTostring(context.Request["tare2"], "0"));
            bmodel.barbelong = context.Request["inDepart"];      //归属地
            bmodel.bargraphic = context.Request["outDepart"];     //处理地
            bmodel.qty = int.Parse(getObjTostring(context.Request["qty"], "0"));
            strtemp = getObjTostring(context.Request["islocak"]);

            if (strtemp != "")
                bmodel.isLocak = true;
            else
                bmodel.isLocak = false;
            bmodel.ParmentID=int.Parse(getObjTostring(context.Request["outid"], "0"));
            bmodel.storageid = int.Parse(getObjTostring(context.Request["storageid"], "0"));
            bmodel.stroageNo = getObjTostring(context.Request["storageno"],"");
            bmodel.packageno = getObjTostring(context.Request["packageno"],"");
            bmodel.rdh = getObjTostring(context.Request["rdh"],"");
            bmodel.remark = getObjTostring(context.Request["remark"]);

            bmodel.InStrorageID = modelins.id;
           
           // bmodel.OutStrorageID = 
            bmodel.status = -1;   //barcode  status 插入时候为-1 提交时候才更改为正式状态 
            bmodel.goodsid = getNumberByobj(context.Request["goodsid"]);
            bmodel.goodscode = getObjTostring(context.Request["goodscode"]);
            bmodel.goodsname = getObjTostring(context.Request["goodsname"]);
            bmodel.rubbishcode = getObjTostring(context.Request["rcode"]);
            bmodel.rubbishtype = getObjTostring(context.Request["rname"]);
            bmodel.plateid = getNumberByobj(context.Request["plateid"]);
            bmodel.plateno = getObjTostring(context.Request["plateno"]);
            bmodel.boxcount = getNumberByobj(context.Request["boxamount"]);
            bmodel.loadnumv = loadnum;
            if (context.Request["barcode"] != null && context.Request["barcode"].Trim() != "")
            {
                bmodel.barcodevalue = context.Request["barcode"].Trim();
            }
            else
            {
               
                bmodel.barcodevalue = Code.NumGeneration.GetSerialNum(bmodel.loadnumv + modelins.wrlno + bmodel.goodscode.PadRight(10, '0'), "BarCode");
            }
            bmodel.id = new DataLib.BLL.BarCode().Add(bmodel);
            return bmodel;

        }

        /// <summary>
        /// 点击修改后返回的数据
        /// </summary>
        /// <param name="barid"></param>
        /// <returns></returns>
        public string GetJsonByBarid(int barid)
        {
            string strjson = "";
            DataLib.Model.BarCode barMode = new DataLib.BLL.BarCode().GetModel(barid);
            if (barMode != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                strjson = serializer.Serialize(barMode);
            }
            return strjson;
        }

        /// <summary>
        /// 当字符串为空 返回默认的值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="def"></param>
        /// <returns></returns>
        public string getObjTostring(object obj, string def)
        {
            string str = getObjTostring(obj);
            if (str == "")
                str = def;
            return str;
        }

        /// <summary>
        /// 当对象为空，返回0
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public int getNumberByobj(object obj)
        {
            if (obj != null && obj.ToString().Trim() != "")
                return int.Parse(obj.ToString());
            else
                return 0;
        }

        /// <summary>
        /// 当对象为空返回 "" 
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string getObjTostring(object obj)
        {
            if (obj != null && obj.ToString().Trim() != "")
                return obj.ToString().Trim();
            else
                return "";
        }

        /// <summary>
        /// 插入领料表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="inModel"></param>
        /// <returns></returns>
        public DataLib.Model.lingniaoItems AddLingniaoItems(HttpContext context,DataLib.Model.InStorage inModel,int? barid)
        {
            DataLib.Model.lingniaoItems lingmodel = new DataLib.Model.lingniaoItems();
            DataLib.BLL.lingniaoItems lingbll = new DataLib.BLL.lingniaoItems();

            lingmodel.outid = int.Parse(getObjTostring(context.Request["outid"], "0"));
            lingmodel.insid = (int)inModel.id;
            lingmodel.insno = inModel.wrlno;
            lingmodel.outsno = getObjTostring(context.Request["outsno"] );
            lingmodel.goodscode = getObjTostring(context.Request["goodscode"]);
            lingmodel.goodsname = getObjTostring(context.Request["goodsname"]);
            lingmodel.nwt = decimal.Parse(getObjTostring(context.Request["gwt"], "0"));
            lingmodel.qty = int.Parse(getObjTostring(context.Request["qty"], "0"));
            lingmodel.remark = getObjTostring(context.Request["remark"]);
            lingmodel.flag1 =barid.ToString();
            lingmodel.flag2 = "";
            lingmodel.flag3 = "";
            lingmodel.flag4 = "";

            if (lingbll.Add(lingmodel) > 0)
            {
                return lingmodel;
            }
            else
            {
                return null;
            }

        }
        /// <summary>
        /// 修改出库单的status
        /// </summary>
        /// <param name="context"></param>
        //public void OutStorageSetStatus(HttpContext context)
        //{
        //   int outid= int.Parse(getObjTostring(context.Request["outid"], "0"));
        //    DataLib.Model.OutStorage outmodel = new DataLib.Model.OutStorage();
        //    DataLib.BLL.OutStorage outbll=   new DataLib.BLL.OutStorage();
        //    outmodel = outbll.GetModel(outid);
        //    if (outmodel != null && outmodel.id > 0)
        //    {
        //        outmodel.status = 11;
        //        outbll.Update(outmodel);
        //    }
                        
        //}

        /// <summary>
        /// 插入生产平衡表
        /// </summary>
        /// <param name="inMode"></param>
        /// <param name="lingMode"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public DataLib.Model.sc_xh AddScXh(DataLib.Model.InStorage inMode, DataLib.Model.lingniaoItems lingMode)
        {
            DataLib.BLL.sc_xh scbll = new DataLib.BLL.sc_xh();
            DataLib.Model.sc_xh scXhModel = new DataLib.Model.sc_xh();

            scXhModel.goodscode = lingMode.goodscode;
            scXhModel.goodsname = lingMode.goodsname;
            scXhModel.nwt_src = lingMode.nwt;
            scXhModel.qty_src = lingMode.qty;
            scXhModel.nwt_jy = 0;
            scXhModel.qty_xh = 0;
            scXhModel.clearmonth = inMode.clearingmonth;
            scXhModel.memo = "";
            scXhModel.flag1 = "";
            scXhModel.flag2 = "";
            scXhModel.flag3 = "";
            scXhModel.insid = (int)inMode.id;
            scXhModel.wrlno = inMode.wrlno;
            scXhModel.outid = lingMode.outid;  //int.Parse(getObjTostring(context.Request["outid"], "0"));
            scXhModel.outno = lingMode.outsno;                  //getObjTostring(context.Request["outsno"]);;


            if (scbll.Add(scXhModel)<=0)
            {
                scXhModel = null;
            }
            return scXhModel;
        }


        //根据id修改称重的信息
        protected string deleteByid(int id)
        {
            string result = "";

            DataLib.BLL.BarCode bll = new DataLib.BLL.BarCode();
            //barcode
            DataLib.Model.BarCode barcodeModel = bll.GetModel(Convert.ToInt32(id));
            if (barcodeModel.status == -1)
            {
                bll.Delete(Convert.ToInt32(id));
                result = "1";
            }
            else
            {
                result = "-1";
            }
            return result;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}